<script lang="ts" setup>
import type { FinanceAdvanceApplication } from '@/api/types/finance'
import type { InfoItem } from '@/components/DetailCard.vue'
import { onLoad } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import { getFinanceAdvanceApplicationById, getFinanceAttachmentByPage } from '@/api/finance'
import { getStatusName } from '@/constants/enums'
import useFlow from '@/hooks/useFlow'
import useLoading from '@/hooks/useLoading'

definePage({
  style: {
    navigationBarTitleText: '预支申请详情',
    enablePullDownRefresh: true,
  },
})

const { loading, startLoading, endLoading } = useLoading()
const flowIdValue = ref<string | null>(null)
const idValue = ref<string | null>(null)
const advanceData = ref<FinanceAdvanceApplication | null>(null)
// 使用流程hook
const {
  currentProcess,
  getProcessInstance,
  getCurrentUserPendingTaskId,
  loading: flowLoading,
} = useFlow()

const basicInfo = computed<InfoItem[]>(() => {
  if (!advanceData.value)
    return []
  return [
    { label: '预支单号', value: advanceData.value.advanceNo || '-' },
    { label: '申请人', value: advanceData.value.applicantName || '-' },
    { label: '申请金额', value: advanceData.value.amountRequested, type: 'currency' },
    { label: '费用类型', value: advanceData.value.receiptEvent || '-' },
    { label: '收款方式', value: advanceData.value.receiveType || '-' },
    { label: '业务机构', value: advanceData.value.businessInstitutionName || '-' },
    { label: '业务部门', value: advanceData.value.businessDepartmentName || '-' },
    { label: '预支用途', value: advanceData.value.purpose || '-', forceMultiline: true },
  ]
})

const businessInfo = computed<InfoItem[]>(() => {
  if (!advanceData.value)
    return []
  return [
    { label: '收款账户类型', value: advanceData.value.receiveAccountType || '-' },
    { label: '收款事项', value: advanceData.value.receiptEvent || '-' },
    { label: '收款公司', value: advanceData.value.receiveCompany || '-' },
    { label: '收款银行', value: advanceData.value.receiveBank || '-' },
    { label: '收款账户', value: advanceData.value.receiveAccount || '-' },
    { label: '提交时间', value: advanceData.value.submitTime || '-' },
  ]
})

const otherInfo = computed<InfoItem[]>(() => {
  if (!advanceData.value)
    return []
  return [
    { label: '制单人', value: advanceData.value.orderMaker || '-' },
    { label: '审批状态', value: getStatusName('advanceApprovalStatus', advanceData.value.approvalStatus || 0) || '-' },
    { label: '是否报销', value: advanceData.value.isReimbursement || '-' },
    { label: '报销金额', value: advanceData.value.claimedAmount, type: 'currency' },
    { label: '退款金额', value: advanceData.value.refundAmount, type: 'currency' },
    { label: '审批时间', value: advanceData.value.approvalTime || '-' },
    { label: '支付时间', value: advanceData.value.paidTime || '-' },
    { label: '打印次数', value: String(advanceData.value.printNum || 0) },
  ]
})

// 费用明细信息 - 重新组织为独立的费用卡片
const expenseDetails = computed<InfoItem[][]>(() => {
  if (!advanceData.value || !advanceData.value.detailList)
    return []

  return advanceData.value.detailList.map((item: any, index: number) => [
    {
      label: '费用类型',
      value: item.name || '-',
      key: `detail-${item.id || index}-name`,
    },
    {
      label: '费用金额',
      value: item.amount,
      key: `detail-${item.id || index}-amount`,
      type: 'currency',
    },
    {
      label: '所属机构',
      value: item.institutionName || '-',
      key: `detail-${item.id || index}-institutionName`,
    },
    {
      label: '所属部门',
      value: item.departmentName || '-',
      key: `detail-${item.id || index}-departmentName`,
    },
    {
      label: '事由',
      value: item.reason || '-',
      key: `detail-${item.id || index}-reason`,
      forceMultiline: true,
    },
    // {
    //   label: '发票类型',
    //   value: getStatusName('invoiceType', item.invoiceType || 0) || '-',
    //   key: `detail-${item.id || index}-invoiceType`,
    // },
    {
      label: '附件',
      value: item.financeAttachmentList || '-',
      key: `detail-${item.id || index}-financeAttachmentList`,
      slot: 'financeAttachmentList',
      forceMultiline: true,
    },
  ])
})

const processInfo = computed(() => {
  if (!currentProcess.value)
    return []
  return [
    { label: '流程实例ID', value: currentProcess.value.id || '-', key: 'processInstanceId', forceMultiline: true },
    // { label: '当前活动', value: currentProcess.value.category || '-' },
    // { label: '流程状态', value: currentProcess.value.status || '-' },
  ]
})

async function getProcessInfo() {
  try {
    flowLoading.value = true
    await getProcessInstance(idValue.value)
    // 获取当前用户待审批任务ID
    const taskId = await getCurrentUserPendingTaskId(idValue.value)
    if (taskId) {
      flowIdValue.value = taskId
    }
  }
  catch (error) {
    console.error('获取流程失败：', error)
  }
  flowLoading.value = false
}

async function loadData() {
  try {
    startLoading()
    await getProcessInfo()
    if (currentProcess.value) {
      const res = await getFinanceAdvanceApplicationById(currentProcess.value.businessKey)
      advanceData.value = res.data || null
      // 根据费用明细id获取对应的发票附件
      endLoading()
      if (advanceData.value.detailList) {
        advanceData.value.detailList.forEach(async (detail, index) => {
        // 获取附件
          const attachments = await getFinanceAttachmentByPage({
            timestamp: Date.now(),
            applicationId: detail.id || '',
            applicationType: '预支',
          })
          detail.financeAttachmentList = attachments.data?.records || []
        })
      }
    }
    else {
      console.error('获取预支申请详情失败: 流程实例不存在业务键')
    }
  }
  catch (error) {
    console.error('获取预支申请详情失败:', error)
  }
  finally {
    endLoading()
  }
}

onLoad((e) => {
  if (e?.flowId) {
    flowIdValue.value = e.flowId || ''
  }
  if (e?.id) {
    idValue.value = e.id || ''
  }
  loadData()
})

onShow(() => {
  if (idValue.value && !flowIdValue.value) {
    getProcessInfo()
  }
})

const tabValue = ref(0)
// 使用uni下拉刷新
onPullDownRefresh(async () => {
  await loadData()
  uni.stopPullDownRefresh()
})
</script>

<template>
  <view class="page">
    <!-- 审批状态卡片 -->
    <ApprovalStatusCard :current-process="currentProcess" :id-value="idValue" />
    <view v-if="loading" class="loading-container">
      <view class="loading">
        加载中...
      </view>
    </view>
    <view v-else-if="advanceData" class="detail-content">
      <wd-tabs v-model="tabValue" swipeable animated sticky :offset-top="0">
        <wd-tab title="基本信息" custom-class="bg-[#f9fafb]" class="" />
        <wd-tab title="费用明细" custom-class="bg-[#f9fafb]" class="" />
      </wd-tabs>
      <view v-if="tabValue === 0" class="bg-[#f9fafb] px-4 py-2.5">
        <!-- 基础信息卡片 -->
        <DetailCard title="基础信息" :info-list="basicInfo" :show-divider="true" />

        <!-- 业务信息卡片 -->
        <DetailCard title="业务信息" :info-list="businessInfo" :show-divider="true" />

        <!-- 其他信息卡片 -->
        <DetailCard title="其他信息" :info-list="otherInfo" :show-divider="true" />

        <!-- 流程信息卡片 -->
        <DetailCard title="流程信息" :info-list="processInfo" :show-divider="true" />
      </view>
      <view v-if="tabValue === 1" class="bg-[#f9fafb] px-4 py-2.5">
        <template v-if="expenseDetails.length > 0">
          <!-- 每个费用明细独立卡片展示 -->
          <view v-for="(cardItems, index) in expenseDetails" :key="`expense-detail-card-${index}`" class="mb-4">
            <DetailCard
              :title="`费用明细 ${index + 1}`"
              :info-list="cardItems"
              :show-divider="false"
            >
              <template #financeAttachmentList="{ value }">
                <view v-if="value.length > 0" class="attachment-container">
                  <AttachmentItem
                    v-for="(item, i) in value" :key="`finance-attachment-${i}`"
                    :file="{
                      name: item.fileName || '-',
                      url: item.filePath || '-',
                    }"
                  />
                </view>
                <view v-else class="mt-4 center c-[#999]">
                  暂无附件
                </view>
              </template>
            </DetailCard>
          </view>
        </template>
        <view v-else class="empty-message">
          暂无费用明细数据
        </view>
      </view>

      <!-- 审批操作按钮区域 -->
      <ApprovalActionBar v-if="flowIdValue && currentProcess?.status === 1" :process-id="flowIdValue" />
    </view>
    <view v-else class="error-container">
      <view class="error-message">
        暂无数据
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.loading-container,
.error-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 50vh;
  color: #999;
}

.detail-content {
  // Tab导航栏样式
  .tab-nav {
    display: flex;
    width: 100%;
    background-color: #fff;
    border-radius: 12rpx 12rpx 0 0;
    margin-bottom: 0;
    overflow-x: auto;
    overflow-y: hidden;
    white-space: nowrap;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
    scrollbar-width: none; /* Firefox */
    -ms-overflow-style: none; /* IE and Edge */

    &::-webkit-scrollbar {
      display: none; /* Chrome, Safari and Opera */
    }
  }

  .tab-item {
    // flex-shrink: 0;
    min-width: 200rpx;
    text-align: center;
    padding: 30rpx 40rpx;
    font-size: 28rpx;
    color: #666;
    border-bottom: 4rpx solid transparent;
    transition: all 0.3s ease;
    cursor: pointer;
    position: relative;
  }

  .tab-item:last-child {
    margin-right: 20rpx;
  }

  .tab-item:first-child {
    margin-left: 20rpx;
  }

  .tab-active {
    color: #1890ff;
    font-weight: 600;
    background-color: #f8f9fa;

    &::after {
      content: '';
      position: absolute;
      bottom: -2rpx;
      left: 50%;
      transform: translateX(-50%);
      width: 60rpx;
      height: 6rpx;
      background-color: #1890ff;
      border-radius: 3rpx;
    }
  }

  // Tab内容区域
  .tab-content {
    background-color: #fff;
    border-radius: 0 0 12rpx 12rpx;
    margin-bottom: 20rpx;
    padding: 0;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  }

  .empty-message {
    text-align: center;
    padding: 80rpx 20rpx;
    color: #999;
    font-size: 26rpx;
  }

  // 费用明细卡片样式
  .expense-details {
    padding: 0;
  }

  .expense-card {
    background-color: #fff;
    border-radius: 12rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
    overflow: hidden;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .expense-amount {
    padding: 20rpx 30rpx;
    background-color: #fafafa;
    border-top: 1px solid #f0f0f0;
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }

  .amount-label {
    font-size: 26rpx;
    color: #666;
  }

  .amount-value {
    font-size: 32rpx;
    color: #ff6b6b;
    font-weight: 600;
    margin-left: 10rpx;
  }

  .section {
    background-color: #fff;
    border-radius: 12rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
  }

  .section-title {
    font-size: 28rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 20rpx;
  }

  .info-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }
  }

  .label {
    font-size: 26rpx;
    color: #666;
  }

  .value {
    font-size: 26rpx;
    color: #333;
    text-align: right;
    flex: 1;
    padding-left: 30rpx;
  }

  .amount {
    color: #ff6b6b;
    font-weight: 600;
    font-size: 32rpx;
  }

  .remark-content {
    font-size: 26rpx;
    color: #666;
    line-height: 1.5;
  }

  .action-buttons {
    margin-top: 30rpx;
    margin-bottom: 40rpx;

    .action-row {
      display: flex;
      justify-content: space-between;
      margin-bottom: 20rpx;

      &:last-child {
        margin-bottom: 0;
      }
    }

    .action-btn {
      flex: 1;
      height: 80rpx;
      border-radius: 12rpx;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 0 10rpx;

      &:first-child {
        margin-left: 0;
      }

      &:last-child {
        margin-right: 0;
      }
    }

    .approve {
      background-color: #4caf50;
      color: white;
    }

    .reject {
      background-color: #f44336;
      color: white;
    }

    .delegate {
      background-color: #2196f3;
      color: white;
    }

    .transfer {
      background-color: #ff9800;
      color: white;
    }

    .add-sign {
      background-color: #9c27b0;
      color: white;
    }
  }
}
</style>
